import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import elib.Bibliotekarz;
import elib.Kierownik;
import elib.Osoba;

@WebServlet("/AddBookServlet")
@MultipartConfig
public class AddBookServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public AddBookServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		//pobieranie sesji
		HttpSession session = request.getSession();
		//pobieranie parametrow z formularza
		String tytul = request.getParameter("title");
		String autor = request.getParameter("author");
		String dataWydania = request.getParameter("date");
		String iloscStron = request.getParameter("pages");
		String ISBN = request.getParameter("isbn");
		String fragment = request.getParameter("fragment");
		Part filePart = request.getPart("file");
		if (session != null && iloscStron!=null && iloscStron.matches("\\d+") && dataWydania.length()>=10) {
			Osoba osoba = (Osoba) session.getAttribute("osoba");
			if (osoba != null) {
				int id=-1;
				if(checkISBN(ISBN)){//warunek poprawnego numeru ISBN
				if(osoba instanceof Kierownik) {
					id = ((Kierownik) osoba).dodajKsiazke(tytul, autor, dataWydania.substring(0, 10), Integer.parseInt(iloscStron), ISBN, fragment);
					response.sendRedirect("admin.jsp?page=addBook");
				} else if(osoba instanceof Bibliotekarz) {
					id = ((Bibliotekarz) osoba).dodajKsiazke(tytul, autor, dataWydania.substring(0, 10), Integer.parseInt(iloscStron), ISBN, fragment);
					response.sendRedirect("librarian.jsp?page=addBook"); 
				}
					} else
					response.sendRedirect("index.jsp");
				if(id!=-1) {
					try {
						InputStream filecontent = filePart.getInputStream();
						OutputStream os = new FileOutputStream(new File("G:\\PROJEKTY\\PROJEKT\\LIBRARY\\eBiblioteka\\WebContent\\books\\"+id+".jpg"));
						int read = 0;										
				        final byte[] bytes = new byte[1024];
				        while ((read = filecontent.read(bytes)) != -1) {
				            os.write(bytes, 0, read);
				        }
				        os.close();
					} catch(Exception e) {
						e.printStackTrace();
					}
				}
			} else
				response.sendRedirect("index.jsp");
		} else
			response.sendRedirect("index.jsp");
		out.close();
	}
	
	 public static boolean checkISBN(String isbn){	
			String ISBN = isbn;
			int checkSum = 0;
					
			if(ISBN.length()==10){
				for (int i=1; i < 10; i++){ // obliczanie sumy kontrolnej ISBN 10
					checkSum = checkSum+((ISBN.charAt(i-1)-48)*i);
				}
				checkSum = checkSum % 11;
					if(checkSum==(ISBN.charAt(9)-48)){// sprawdzanie ISBN 10
						System.out.println("ISBN 10 - poprawny");
						return true;
				}else{
					System.out.println("ISBN 10 - niepoprawny");
					return false;
				}
			}if(ISBN.length()==13){
				checkSum = ( (ISBN.charAt(0)-48)+(ISBN.charAt(2)-48)+(ISBN.charAt(4)-48)+(ISBN.charAt(6)-48)+(ISBN.charAt(8)-48)+(ISBN.charAt(10)-48)
						+ (3*((ISBN.charAt(1)-48)+(ISBN.charAt(3)-48)+(ISBN.charAt(5)-48)+(ISBN.charAt(7)-48)+(ISBN.charAt(9)-48)+(ISBN.charAt(11)-48))));
				checkSum = 10-(checkSum % 10);
				checkSum = checkSum % 10;
					if(checkSum==(ISBN.charAt(12)-48)){
						System.out.println("ISBN 13 - poprawny!");
						return true;
					}else{
						System.out.println("ISBN 13 - nieporapwny!");		
						return false;}
			}else{
				System.out.println("Niepoprawnie wprowadzony numer ISBN");
				return false;
			}
		    }
	
}